package se.peterbjorkman.android.trafikkamera;

import java.util.Date;

import se.peterbjorkman.android.trafikkamera.DownloadImageTask.Callback;
import se.peterbjorkman.android.trafikkamera.providers.CameraContentProvider;
import se.peterbjorkman.android.trafikkamera.providers.CameraDefs;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

//http://developer.android.com/intl/zh-CN/guide/tutorials/views/hello-gallery.html
public class CameraPictureActivity extends Activity {
	
	public static final String EXTRA_ID = "se.peterbjorkman.android.trafikkamera.vadddd";
	private static final int ADD_TO_ROUTE_MENU_ID = Menu.FIRST;
	private static final int AddToRouteRequestCode = 1;
	private CameraView mView;
	private long _id;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().requestFeature(Window.FEATURE_PROGRESS);

		final CameraView view = new CameraView(this);
		view.setLayoutParams(new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        
		mView = view;
		setContentView(view);

		long id = getIntent().getLongExtra(EXTRA_ID, 0);
		_id = id;
		
		Data data = readDataFromProvider(id);
		
		if (data == null){
			finish();
			return;
		}
		
		String title = getTitle().toString();
		title += " - " + data.Name;
		setTitle(title);
		
		view.setDescription(data.Description);
		Bitmap map = null;
		if (savedInstanceState != null)
			map = (Bitmap)savedInstanceState.getParcelable("image");
	
		if (map == null)
		{
			view.setModifiedText("");
			DownloadImageTask test = new DownloadImageTask(this, new Callback() {
				
				@Override
				public void modifiedTimeCallback(Date date) {
					view.setModifiedText(date.toLocaleString());
				}
				
				@Override
				public void imageCallback(BitmapDrawable drawable) {
					view.hideAllProgressIndication();
					view.setImage(drawable);
				}

				@Override
				public void progressCallback(int done, int total) {
					view.setProgress(done, total);
				}

				@Override
				public void statusCallback(String status) {
					view.setProgressStatus(status);
				}
			});
			test.execute(data.Url);
		}
		else
		{
			view.setImage(new BitmapDrawable(map));
			view.setModifiedText(savedInstanceState.getString("modified"));
		}
	}
	
	private Data readDataFromProvider(long id) {
		// TODO small or normal picture size?
		String urlColumn = CameraDefs.CAMERA_URL;
		
		String[] projection = new String[] { 
				CameraDefs.NAME,
				CameraDefs.DESCRIPTION,
				urlColumn ,
				CameraDefs.ROAD};
		
		String filter = CameraDefs.ID + " = " + id;
		
        Cursor c = managedQuery(
        		CameraContentProvider.CONTENT_URI, 
        		projection, 
        		filter, 
        		null, 
        		null);
        
        if (c.moveToFirst()) {
        	Data data = new Data();
        	data.Name = c.getString(c.getColumnIndex(CameraDefs.NAME));
        	data.Url = c.getString(c.getColumnIndex(urlColumn));
        	data.Description = c.getString(c.getColumnIndex(CameraDefs.DESCRIPTION));
        	return data;
        	
        } else {
        	return null;
        }
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) 
	{
		if (mView == null)
			return;
			
		BitmapDrawable drawable = (BitmapDrawable)mView.getDrawable();
		if (drawable == null)
			return;
		
		outState.putParcelable("image", drawable.getBitmap());
		String modifed = mView.getModifiedText();
		
		outState.putString("modified", modifed);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Log.d(LOGTAG, "In onCreateOptionsMenu");
        
        super.onCreateOptionsMenu(menu);

        if (SelectRouteActivity.shouldBeShown(_id, this))
        	menu.add(0, ADD_TO_ROUTE_MENU_ID, 0, "Lägg till i rutt")
            	;//.setIcon(R.drawable.menu_update);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //Log.d(LOGTAG, "In onOptionsItemSelected");
     
        switch (item.getItemId()) {
        case ADD_TO_ROUTE_MENU_ID:
        	AddToRoute();
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
	

	private void AddToRoute() {
		long id = getIntent().getLongExtra(EXTRA_ID, 0);
		Intent intent = new Intent(this, SelectRouteActivity.class);
		intent.putExtra(SelectRouteActivity.EXTRA_ID, id);
		startActivityForResult(intent, AddToRouteRequestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent){
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_CANCELED)
			return;
		
		switch (requestCode){
			case AddToRouteRequestCode:
				HandleAddToRoute(intent);
			break;
			default:
		}
	}
	
	private void HandleAddToRoute(Intent intent) {
		long routeId =  intent.getLongExtra(SelectRouteActivity.SELECTEDID, 0);
		long cameraId = intent.getLongExtra(SelectRouteActivity.EXTRA_ID,   0);
		
		ContentResolver cr = getContentResolver();

        ContentValues values = new ContentValues();
        values.put("cameraid",       cameraId); // TODO hardcoded column names
        values.put("routeid",        routeId);
        values.put("sortorder",      0); // TODO sortorder
        
        cr.insert(CameraContentProvider.CAMERAROUTES_URI, values); 
	}

	private class Data{
		public String Name;
		public String Url;
		public String Description;
	}
}
